use crate::logger;
use anyhow::Result;
use serde_json::Value;
use std::fs;
use crate::project::DependenciesMod;

pub fn update_project_basic_info(
    project_dir: &std::path::PathBuf,
    project_name:String,
) -> Result<()> {
    let mut path = std::path::PathBuf::from(project_dir);
    path.push("package.json");

    let package_json: String = std::fs::read_to_string(&path)?;
   // 解析 JSON 数据
    let mut parsed_json: Value = serde_json::from_str(&package_json)?;

    if !project_name.is_empty() {
        // 修改 "name" 属性
        if let Some(name) = parsed_json.get_mut("name") {
            *name = Value::String(project_name);
        } else {
            // 如果没有 "name" 属性，则添加它
            parsed_json.as_object_mut().unwrap().insert("name".to_string(), Value::String("demo".to_owned()));
        }
    }
    parsed_json.as_object_mut().unwrap().insert("version".to_string(), Value::String("0.1.0".to_owned()));
    // 将修改后的 JSON 转换为字符串
    let modified_json_string = serde_json::to_string_pretty(&parsed_json)?;
    // 将新的 JSON 内容写回文件，覆盖原有内容
    fs::write(path, modified_json_string)?;

    Ok(())
}


pub fn add_dependency_to_package_json(
    project_dir: &std::path::PathBuf,
    dependency_name: &str,
    dependency_version: &str,
    mode:DependenciesMod,
) -> Result<(), std::io::Error> {
    logger::add_dependency_msg(dependency_name);
    let mut path = std::path::PathBuf::from(project_dir);
    path.push("package.json");

    let package_json: String = std::fs::read_to_string(&path)?;

   // 解析 JSON 数据
    let mut parsed_json: Value = serde_json::from_str(&package_json)?;
    let dev_or_pro = match mode {
        DependenciesMod::Dev => "devDependencies".to_string(),
        DependenciesMod::Prod => "dependencies".to_string(),
    };
    // 修改 "dependencies" 对象
    let deps = parsed_json.get_mut(
        dev_or_pro.as_str()).and_then(|d| d.as_object_mut()
    ).unwrap();
    deps.insert(dependency_name.to_string(), Value::String(dependency_version.to_owned()));
     // 将修改后的 JSON 转换为字符串
    let modified_json_string = serde_json::to_string_pretty(&parsed_json)?;

    // 将新的 JSON 内容写回文件，覆盖原有内容
    fs::write(path, modified_json_string)?;

    Ok(())
}


